<template>
  <el-dialog :visible.sync="isShow" v-if="isShow" title="菜单权限" width="50%" :before-close="handleClose" top="100px"
  :close-on-click-modal="false">
    <div class="flexStartDetween">
      <p v-show="formParams">角色名称：【<span style="color: red;font-size: 18px;">{{formParams.role_name}}</span>】</p>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleClose">取 消</el-button>
        <el-button size="medium" type="primary" @click="handleConfirm()">确 定</el-button>
      </span>
    </div>
    <div class="border-box" style="max-height: 600px;overflow: auto;">
      <el-input class="marginB10" v-model="menuKey" clearable placeholder="输入菜单名称"/>
      <el-tree
        ref="menuTree"
        node-key="id"
        :data="menuDataList"
        show-checkbox
        :default-expand-all="true"
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @check="handleCheckChange">
      </el-tree>
    </div>
  </el-dialog>
</template>

<script>
import {
  roleMenuAdd
} from '@/api/system.js'
export default {
  props: {
  	show: {
  		type: Boolean,
  		default: false
  	},
  	data: {
  		type: Object,
  		default: function() {
  			return {}
  		}
  	},
  },
  data() {
    return {
      isShow:false,
      formParams:{},
      menuKey:'',
      userInfo:this.$store.state.user.userInfo,
      menuDataList:[],
      chooseMenuKey:[],
      checkedKeys:[],
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'status',
      },
    }
  },
  watch: {
  	show: function() {
  		let that = this;
  		that.isShow = that.show
  		if (that.data) {
  			that.formParams = JSON.parse(JSON.stringify(that.data))
  		}else{
        that.formParams={}
      }
      that.getMenuList()
  	},
    menuKey(val) {
      this.$refs.menuTree.filter(val);
    }
  },
  methods: {
    // 菜单权限
    getMenuList(){
      let that = this,menu=[],params = JSON.parse(JSON.stringify(that.formParams));
      that.chooseMenuKey=[]
      that.checkedKeys=[]
      that.menuList = that.userInfo.menu_data
      // 菜单权限
      if(params.menu_ids){
        let arrChoose = [], arrChecked = [];
        menu=params.menu_ids.split(',')
        // 默认选中的权限
        menu.map(item=>{
          arrChoose.push(Number(item))
          arrChecked.push(Number(item))
        })
        // 父节点ID
        let pId= [-2],cId=[];
        that.menuList.forEach((item) => {
          if (item.parent_id) {
            if (pId.indexOf(item.parent_id) < 0) {
              pId.push(item.parent_id)
            }
          }
        })
        // 默认选中的权限
        that.menuList.map(item=>{
          if(!!~arrChoose.indexOf(item.id)){
            if(!item.children?.length){
              arrChecked.push(item.id)
            }
          }
        })
        arrChecked=Array.from(new Set(arrChecked));
        arrChecked.map((item,index)=>{
          if(!~pId.indexOf(item)){
            cId.push(item)
          }
        })
        that.$nextTick(()=>{
          that.chooseMenuKey=JSON.parse(JSON.stringify(arrChoose))
          that.checkedKeys=JSON.parse(JSON.stringify(cId))
          // console.log(arrChoose,cId);
        })
      }
      that.menuDataList= [{id: -2,label: '全选', children: that.recursiveTree(that.userInfo.menu_data)}]
    },
    handleExpand() {
      // 节点被展开时触发的事件
      // 因为该函数执行在renderContent函数之前，所以得加this.$nextTick()
      this.$nextTick(() => {
        this.changeCss()
      })
    },
    // 筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 选择节点
    handleCheckChange(val,data){
      this.chooseMenuKey=[...data.checkedKeys,...data.halfCheckedKeys]
    },
    // 递归处理菜单(递归函数)
    recursiveTree(menuList = []){
      function loop(key, dep=1) {
        const arr = []
        menuList?.forEach(item => {
          if(item.parent_id == key){
            item.dep = dep
            item.label = item.name
            item.children = loop(item.id, dep + 1)
            arr.push(item)
          }
        })
        return arr
      }
      return loop(0)
    },
    loop(val){
      return JSON.parse(JSON.stringify(val))
    },
    // 确认
    handleConfirm() {
      let that=this,params=JSON.parse(JSON.stringify(that.formParams));
      if(that.chooseMenuKey?.[0]<0){
        that.chooseMenuKey.splice(0,1,)
      }
      roleMenuAdd({
        id:params.id,
        menu_ids:that.chooseMenuKey.toString()
      }).then(function(res) {
        that.$message.success(res.msg)
        that.$emit('onHideDetails',true)
      }).catch((error)=>{
        that.$message.error(error.msg)
      })
    },
    // 取消
    handleClose() {
    	this.$emit('onHideDetails',false)
    },
  }
}
</script>

<style scoped lang="scss">

</style>
